﻿#if UNITY_ANDROID && !UNITY_EDITOR
using UnityEngine;
#endif

namespace BToolkit
{
    public class AndroidHelper
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        private static AndroidJavaObject _mainActivity;
        private static AndroidJavaObject mainActivity
        {
            get
            {
                if (_mainActivity == null)
                {
                    AndroidJavaClass javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                    _mainActivity = javaClass.GetStatic<AndroidJavaObject>("currentActivity");
                }
                return _mainActivity;
            }
        }
#endif

        /// <summary>
        /// 当前设备安卓版本
        /// </summary>
        /// <returns></returns>
        public static int GetAndroidSDKVersion()
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            return CallMainActivityFunction<int>("getAndroidSDKVersion");
#else
            return 0;
#endif
        }

        /// <summary>
        /// 调用Java(Android)层MainActivity类的函数
        /// </summary>
        public static void CallMainActivityFunction(string functionName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            mainActivity.Call(functionName, args);
#endif
        }

        /// <summary>
        /// 调用Java(Android)层MainActivity类的函数，有返回值
        /// </summary>
        public static T CallMainActivityFunction<T>(string functionName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            if(args == null)
            {
                return mainActivity.Call<T>(functionName);
            }
            else
            {
                return mainActivity.Call<T>(functionName, args);
            }
#else
            return default(T);
#endif
        }

        /// <summary>
        /// 调用Java(Android)层的静态函数，无返回值
        /// </summary>
        public static void CallStaticFunction(string classPath, string methodName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass jc = new AndroidJavaClass(classPath);
            jc.CallStatic(methodName, args);
#endif
        }

        /// <summary>
        /// 调用Java(Android)层的静态函数，有返回值
        /// </summary>
        public static T CallStaticFunction<T>(string classPath, string methodName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass jc = new AndroidJavaClass(classPath);
            return jc.CallStatic<T>(methodName, args);
#else
            return default(T);
#endif
        }

    }
}